package com.example.shopdemo.service;

import com.example.shopdemo.dto.WechatAuthExecution;
import com.example.shopdemo.entity.PersonInfo;
import com.example.shopdemo.entity.WechatAuth;
import com.example.shopdemo.enums.WechatAuthStateEnum;
import com.example.shopdemo.repository.PersonInfoRepository;
import com.example.shopdemo.repository.WechatAuthRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * @author ：Anitaxiaofeng
 * @description：
 * @create 2018-02-04
 **/
@Service
public class WechatAuthServiceImpl {


    @Autowired
    private WechatAuthRepository wechatAuthRepository;

    @Autowired
    private PersonInfoRepository personInfoRepository;

    //通过openId查找平台对应的微信账号
    public WechatAuth getWechatAuthByOpenId(String openId){
        return wechatAuthRepository.findByOpenId(openId);
    }


    @Transactional
    public WechatAuthExecution register(WechatAuth wechatAuth, PersonInfo personInfo)throws RuntimeException{
        if(wechatAuth==null||wechatAuth.getOpenId()==null){
            return new WechatAuthExecution(WechatAuthStateEnum.NULL_AUTH_INFO);
        }
        wechatAuth.setCreateTime(new Date());
        if(personInfo!=null&&wechatAuth.getUserId()==null){
            personInfo.setCreateTime(new Date());
            PersonInfo personInfoResult = personInfoRepository.save(personInfo);
            if(personInfoResult==null){
                throw new RuntimeException("添加personInfo失败");
            }
            wechatAuth.setUserId(personInfoResult.getUserId());
            WechatAuth wechatAuthResult = wechatAuthRepository.save(wechatAuth);
            if(wechatAuthResult==null){
                throw new RuntimeException("添加wechatAuthRepository失败");
            }else{
                return new WechatAuthExecution(WechatAuthStateEnum.SUCCESS,wechatAuthResult);
            }
        }
        return new WechatAuthExecution(WechatAuthStateEnum.NULL_AUTH_INFO);
    }

}




